import 'package:cbec_app/components/base/base_interactive.dart';
import 'package:cbec_app/components/common/common_style.dart';
import 'package:cbec_app/components/order/order_goods_item.dart';
import 'package:cbec_app/components/popup/after_sales_popup.dart';
import 'package:cbec_app/pages/my/controller/my_order_ctr.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_typedefs/rx_typedefs.dart';
import '../../pages/goods/view/custom_countdown_timer.dart';

class OrderItem extends StatelessWidget {
  ///订单ID
  final String id;

  final bool? hasBonded;

  ///订单号
  final String orderSn;

  ///支付单号
  final String? paySn;

  ///订单号
  final String? sn;

  ///订单时间
  final String orderTime;

  ///订单金额
  final double totalAmount;

  ///实付款
  final double? priceOrder;

  ///订单状态 1、待支付、2、待收货 、3、已取消 4、已完成、5、待评价、6、售后
  ///
  final int status;

  ///订单商品列表
  final List goodsList;

  ///是否是预售订单
  bool isPresale;

  ///预售订单数据
  var presaleData;

  /// 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
  final int? type;

  final int? returnStatus;

  // 用于全部订单是否展示去评价
  final bool? isHideComment;

  final bool? isShowSpec;

  OrderItem({
    super.key,
    required this.orderSn,
    required this.orderTime,
    required this.totalAmount,
    required this.status,
    required this.goodsList,
    required this.id,
    this.sn = '',
    this.paySn = '',
    this.priceOrder = 0,
    this.isPresale = false,
    this.presaleData,
    this.type,
    this.returnStatus,
    this.isHideComment = false,
    this.isShowSpec = true,
    this.hasBonded = false,
  });

  late Widget actionButtons; //操作按钮组
  late Widget statusWidget; //右上角的状态

  final MyOrderController controller = Get.put(MyOrderController());

  //是否是预售订单
  bool isPresaleOrder() {
    if (presaleData == null) {
      return false;
    }
    return (isPresale && presaleData['presaleType'] != 1 && presaleData['finalStatus'] != 1);
  }

  @override
  Widget build(BuildContext context) {
    //渲染构建
    switch (status) {
      case 10:
        if (isPresaleOrder()) {
          actionButtons = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            mainAxisSize: MainAxisSize.max,
            children: [
              if (presaleData['presaleType'] == 2) ...[
                // 定金预售，支付定金，支付尾款，已经在待发货的状态了，这里不处理
                SizedBox(
                  height: 30.h,
                  child: _buttons("取消订单", color: "#333333", () {
                    controller.cancelOrder(id);
                  }),
                ),
                const SizedBox(width: 5),
                SizedBox(
                  height: 30.h,
                  child: _buttons("支付定金", color: "#F83F2D", () {
                    Get.toNamed(
                      '${Routes.cashier}/?sn=$paySn&price=$priceOrder&cd=${presaleData['cd']}',
                      arguments: {'hasBonded': hasBonded},
                    );
                  }),
                ),
              ] else if (presaleData['presaleType'] == 1) ...[
                // 全款预售，待支付
                SizedBox(
                  height: 30.h,
                  child: _buttons("取消订单", color: "#333333", () {
                    controller.cancelOrder(id);
                  }),
                ),
                const SizedBox(width: 5),
                SizedBox(
                  height: 30.h,
                  child: _buttons("继续支付", color: "#333333", () {
                    Get.toNamed(
                      '${Routes.cashier}/?sn=$paySn&price=$priceOrder&cd=${presaleData['cd']}',
                      arguments: {'hasBonded': hasBonded},
                    );
                  }),
                ),
              ],
            ],
          );

          statusWidget = Tools.isPresaleEnded(presaleData['presaleEndTime'])
              ? const SizedBox()
              : SizedBox(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Container(
                        padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                        decoration: BoxDecoration(color: Tools.fromHex("#F83F2D"), borderRadius: const BorderRadius.horizontal(left: Radius.circular(20.0))),
                        child: const Text("等待付款", style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w300)),
                      ),
                      Container(
                        padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                        decoration: BoxDecoration(color: Tools.fromHex("#FFC7C7"), borderRadius: const BorderRadius.horizontal(right: Radius.circular(20.0))),
                        child: CustomCountdownTimer(endTime: DateTime.parse(presaleData['pendingPaymentTime']), onEnd: () {}),
                      ),

                      //CustomCountdownTimer(endTime: DateTime.parse(widget.itemInfo['pendingPaymentTime']), onEnd: () {}),
                    ],
                  ),
                );

          // Expanded(
          //         child: Text(
          //           "${presaleData['presaleEndTime'] != null ? presaleData['presaleEndTime'] + "前请支付尾款" : ""}",
          //           maxLines: 2,
          //           style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Colors.red),
          //         ),
          //       );
        } else {
          //待支付
          actionButtons = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              _buttons("取消订单", color: "#333333", () {
                controller.cancelOrder(id);
              }),
              const SizedBox(
                width: 10,
              ),
              _buttons("继续付款", color: "#F83F2D", () {
                Get.toNamed(
                  '${Routes.cashier}/?sn=$paySn&price=$totalAmount&cd=$orderTime',
                  arguments: {'hasBonded': hasBonded},
                );
              }),
            ],
          );

          statusWidget = SizedBox(
            child: Row(
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                  decoration: BoxDecoration(color: Tools.fromHex("#F83F2D"), borderRadius: const BorderRadius.horizontal(left: Radius.circular(20.0))),
                  child: const Text("等待付款", style: TextStyle(color: Colors.white, fontSize: 10, fontWeight: FontWeight.w300)),
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(4.w, 2.w, 4.w, 2.w),
                  decoration: BoxDecoration(color: Tools.fromHex("#FFC7C7"), borderRadius: const BorderRadius.horizontal(right: Radius.circular(20.0))),
                  child: CustomCountdownTimer(endTime: DateTime.parse(orderTime).add(const Duration(minutes: 15)), onEnd: () {}),
                ),
              ],
            ),
          ); //这里是待支付的组件
        }

        break;

      case 20:
        //待发货
        if (isPresaleOrder()) {
          actionButtons = Tools.isPresaleEnded(presaleData['presaleEndTime'])
              ? const SizedBox()
              : Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    _buttons("申请售后", color: "#333333", () {
                      afterSalesPopup(context, goodsList, id, afterSaleStyle: 2);
                    }),
                    const SizedBox(width: 10),
                    _buttons("支付尾款", color: "#333333", () {
                      Get.toNamed(Routes.pendingPayment, arguments: id);
                    }),
                  ],
                );
        } else {
          actionButtons = Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              _buttons("申请售后", color: "#333333", () {
                afterSalesPopup(context, goodsList, id, afterSaleStyle: 2);
              })
            ],
          );
        }
        statusWidget = Text("待发货", style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#F83F2D")));
        break;

      case 30:
        //待收货
        actionButtons = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            _buttons("申请售后", color: "#333333", () {
              afterSalesPopup(context, goodsList, id, afterSaleStyle: 1);
            }),
            const SizedBox(
              width: 10,
            ),
            _buttons("确认收货", color: "#F83F2D", () {
              Tools.showModal(
                content: "确认要收货么?",
                onCancel: (tag) => {},
                onConfirm: (tag) {
                  controller.receive(id);
                  SmartDialog.dismiss(tag: tag);
                },
              );
            }),
          ],
        );
        statusWidget = Text("待收货", style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#F83F2D")));
        break;
      case 0:
        //已取消
        actionButtons = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            _buttons("删除订单", color: "#333333", () {
              controller.deleteOrder(id);
            }),
            const SizedBox(
              width: 10,
            ),
            _buttons("再次购买", color: "#F83F2D", () {
              controller.argin(
                goodsList,
                type!,
              );
            }),
          ],
        );
        statusWidget = Text("已取消", style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#999999")));
        break;
      case 50:
        //已完成
        actionButtons = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            _buttons("再次购买", color: "#F83F2D", () {
              controller.argin(
                goodsList,
                type!,
              );
            }),
            const SizedBox(
              width: 10,
            ),
            _buttons("申请售后", color: "#333333", () {
              afterSalesPopup(context, goodsList, id, afterSaleStyle: 1);
            }),
            const SizedBox(
              width: 10,
            ),
          ],
        );

        statusWidget = Text("已完成", style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#F83F2D")));

        break;
      case 40:
        //待评价
        actionButtons = const Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            // _buttons("评价", color: "#F83F2D", () {
            //   Get.toNamed(Routes.commentOrderList);
            // }),
          ],
        );

        statusWidget = Text("已签收", style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#F83F2D")));

        break;
      case 6:
        RefundStatus? currentRefundStatus = RefundStatusExtension.fromInt(returnStatus!);
        final returnStatusStr = RefundStatusExtension.fromInt(returnStatus!)?.description ?? '';
        //售后
        actionButtons = Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            if (currentRefundStatus == RefundStatus.shippedAwaitingBuyerReceipt)
              Row(
                mainAxisAlignment: MainAxisAlignment.end,
                children: <Widget>[
                  _buttons("确认收货", color: "#F83F2D", () {
                    Tools.showModal(
                      content: "确认要收货么?",
                      onCancel: (tag) => {},
                      onConfirm: (tag) {
                        controller.orderReturnReceive(id);
                        SmartDialog.dismiss(tag: tag);
                      },
                    );
                  }),
                  SizedBox(
                    width: 10.w,
                  ),
                ],
              ),
            _buttons("上传物流", color: "#333333", () {
              Get.toNamed(Routes.afterSalesDetail, arguments: id);
            }),
          ],
        );

        statusWidget = Text(returnStatusStr, style: TextStyle(fontSize: 11, fontWeight: FontWeight.w300, color: Tools.fromHex("#F83F2D")));
        break;
      default:
        statusWidget = Container();
    }

    return BaseInteractive(
      onClick: () => {_toPages()},
      childWidget: Container(
        margin: EdgeInsets.only(bottom: 10.w),
        decoration: border_radis(Colors.white),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            //标题栏
            Container(
              padding: EdgeInsets.all(10.w),
              // height: 28,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Flexible(
                    child: Text(
                      "订单编号:$sn",
                      style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w300),
                      overflow: TextOverflow.ellipsis, // 使文字内容溢出时显示省略号
                      maxLines: 2, // 最多显示2行
                    ),
                  ),
                  statusWidget,
                ],
              ),
            ),
            //订单的商品列表
            Container(
              padding: EdgeInsets.only(left: 10.w, right: 10.w),
              child: Column(
                children: [
                  //这里面是商品
                  for (var goodsItem in goodsList)
                    OrderGoodsItem(
                      refundAmount: goodsItem['priceReturn'] ?? 0,
                      refundNum: goodsItem['returnNumber'] ?? 1,
                      goodsImg: goodsItem['img'] ?? '',
                      title: goodsItem['goodsName'] ?? '',
                      tagType: goodsItem['commodityType'] ?? 0,
                      price: goodsItem['price'] ?? 0.00,
                      num: goodsItem['buyNum'] ?? 0,
                      totalAmount: totalAmount,
                      status: status,
                      isComment: isHideComment == true ? 1 : goodsItem['isComment'],
                      channelID: goodsItem['goodsId'] ?? '',
                      orderID: id,
                      paySn: paySn ?? '',
                      sn: sn ?? '',
                      star: goodsItem['channelStars'],
                      comment: goodsItem['commentText'],
                      unit: goodsItem['unit'],
                      isShowSpec: isShowSpec,
                      spuSpecBody: goodsItem['spuSpecBody'] ?? '',
                    ),
                  //这里是实付款
                  if (isPresaleOrder()) ...[
                    if (presaleData['presaleType'] == 2) ...[
                      SizedBox(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            const Text(
                              "实付款",
                              style: TextStyle(fontSize: 12, fontWeight: FontWeight.w300),
                            ),
                            Text(
                              "￥$priceOrder",
                              style: TextStyle(color: Tools.fromHex("#F83F2D"), fontSize: 15, fontWeight: FontWeight.w300),
                            )
                          ],
                        ),
                      )
                    ] else ...[
                      SizedBox(
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            Text(
                              status == 0 ? "实付款" : "待支付尾款金额",
                              style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w300),
                            ),
                            Text(
                              status == 0 ? "￥$priceOrder" : "￥${presaleData['finalPay']}",
                              style: TextStyle(color: Tools.fromHex("#F83F2D"), fontSize: 15, fontWeight: FontWeight.w300),
                            )
                          ],
                        ),
                      )
                    ]
                  ] else ...[
                    status != 4 && status != 6
                        ? SizedBox(
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.end,
                              children: [
                                const Text(
                                  "实付款",
                                  style: TextStyle(fontSize: 12, fontWeight: FontWeight.w300),
                                ),
                                Text(
                                  "￥$priceOrder",
                                  style: TextStyle(color: Tools.fromHex("#F83F2D"), fontSize: 15, fontWeight: FontWeight.w300),
                                )
                              ],
                            ),
                          )
                        : emptyWidget(),
                  ],
                  //这里是按钮
                  Container(margin: EdgeInsets.only(top: 10.w, bottom: 10.w), child: actionButtons)
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /**
   * 按钮
   */
  Widget _buttons(
    String title,
    Callback onPressed, {
    String? color = "#cccccc",
    double? height = 28,
    double? fontsize = 13,
    EdgeInsets? margin,
  }) {
    return Container(
      margin: margin ?? margin,
      height: height,
      child: OutlinedButton(
          style: OutlinedButton.styleFrom(
            padding: EdgeInsets.fromLTRB(10.w, 3.w, 10.w, 3.w),
            side: BorderSide(color: Tools.fromHex(color!)), // 设置边界颜色
          ),
          onPressed: onPressed,
          child: Text(
            title,
            style: TextStyle(fontSize: 13, color: Tools.fromHex(color), fontWeight: FontWeight.w500),
          )),
    );
  }

  //根据不同的订单状态跳转到对应的页面
  //订单状态 1、待支付、2、待收货 、3、已取消 4、已完成、5、待评价、6、售后
  void _toPages() {
    if (status == 6 || status == 7) {
      Get.toNamed(Routes.afterSalesDetail, arguments: id);
    } else {
      if (isPresaleOrder()) {
        // Get.toNamed('${Routes.cashier}/?sn=$paySn&price=${presaleData['finalPay']}&cd=$orderTime');
        Get.toNamed(Routes.pendingPayment, arguments: id);
      } else {
        Get.toNamed(Routes.pendingPayment, arguments: id);
      }
    }
  }
}
